package com.chucang.shucang.ttp.service;

import cn.hutool.core.util.ArrayUtil;
import com.chucang.shucang.common.mq.message.SmsCodeMessage;
import com.chucang.shucang.ttp.messagecenter.enums.MESSAGE_TYPE;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20190711.models.SendStatus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Optional;

/**
 * @author flitsneak
 * @email flitsneak@gmail.com
 * @date 2022/9/26 21:58
 * @description 腾讯云短信
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TencentSmsService {
    @Value("${tencent.sms.smsSdkAppId}")
    private String smsSdkAppId;

    @Value("${tencent.sms.templateId}")
    private String templateId;

    @Value("${tencent.sms.signName}")
    private String signName;

    private final SmsClient smsClient;

    public boolean sendMessage(MESSAGE_TYPE messageType, SmsCodeMessage smsCodeMessage) {

        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setSmsSdkAppid(smsSdkAppId);
        sendSmsRequest.setTemplateID(templateId);
        sendSmsRequest.setSign(signName);
        sendSmsRequest.setPhoneNumberSet(new String[]{"+86" + smsCodeMessage.getMobile()});
        sendSmsRequest.setTemplateParamSet(new String[]{smsCodeMessage.getSmsCode()});

        try {
            SendSmsResponse sendSmsResponse = smsClient.SendSms(sendSmsRequest);
            SendStatus[] sendStatuses = Optional.ofNullable(sendSmsResponse.getSendStatusSet()).get();
            if (ArrayUtil.isEmpty(sendStatuses)) {
                return false;
            }
            SendStatus sendStatus = Arrays
                    .stream(sendStatuses)
                    .findFirst()
                    .get();
            if (!sendStatus.getCode().equals("Ok")) {
                log.error("腾讯云发送短信异常====>{},异常内容{}", sendStatus.getMessage(), smsCodeMessage);
                return false;
            }
        } catch (TencentCloudSDKException e) {
            log.error("腾讯云短信发送异常，异常信息{}，异常内容{}", e.getMessage(), smsCodeMessage);
            return false;
        }
        return true;
    }
}
